import re
import time
from openai import OpenAI
from minio import Minio
import datetime

# API 配置
BASE_URL, STEP_API_KEY = "https://api.stepfun.com/v1", "5I046FcXrnQhXJreXQrR78su7Z9FvbyUoJMtVDIXsCzkfrifyKgMUAN0cfBGnK9KP"
COMPLETION_MODEL = "step-1o-turbo-vision"

# 用户问题提示
user_prompt = "帮我看看视频里面的人，坐在驾驶位上的驾驶员，此人有没有 不系安全带，打电话，抽烟，闭眼2秒以上，喝饮料，吃食物，玩手机，打哈欠，双手同时脱离方向盘1秒以上，头部左看右看3秒以上？返回最简洁的json结果，里面包含可信度百分比。"
user_prompt = "请逐帧分析视频中驾驶位驾驶员行为，检测以下几项内容：1.不系安全带 2.打电话 3.抽烟 4.闭眼≥2秒 5.喝饮料 6.吃食物 7.玩手机 8.双手脱离方向盘≥1秒 9.头部左右张望≥3秒。返回JSON需包含：行为名称(name)、是否发生(occurred)、可信度(confidence 0-100%)、首次发生时间(time_occurred)。时间戳格式[分:秒.毫秒]，未发生则为null。仅返回JSON。"
user_prompt = """请逐帧分析视频中驾驶位驾驶员行为，检测以下几项内容：1.不系安全带 2.打电话 3.抽烟 4.闭眼≥2秒 5.喝饮料 6.吃食物 7.玩手机 8.双手脱离方向盘≥1秒 9.头部左右张望≥3秒 10.打哈欠。返回JSON需包含：行为名称(name)、是否发生(occurred)、可信度(confidence 0-100%)、首次发生时间(time_occurred)。时间戳格式[分:秒.毫秒]，未发生则为null。仅返回JSON。
json格式示例：
{
    "behaviors": [
        {
            "name": "不系安全带",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        },
        {
            "name": "打电话",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        },
        {
            "name": "抽烟",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        },
        {
            "name": "闭眼≥2秒",
            "occurred": true,
            "confidence": 90,
            "time_occurred": "[17:49.57-18:49.57]"
        },
        {
            "name": "喝饮料",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        },
        {
            "name": "吃食物",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        },
        {
            "name": "玩手机",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        },
        {
            "name": "双手脱离方向盘≥1秒",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        },
        {
            "name": "头部左右张望≥3秒",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        },
        {
            "name": "打哈欠",
            "occurred": false,
            "confidence": 100,
            "time_occurred": "null"
        }
    ]
}
"""

# 初始化 MinIO 客户端
minio_client = Minio(
    "101.132.64.6:10005",
    access_key="okonoff",
    secret_key="okonoff1234",
    secure=False
)

bucket_name = "aifile"
base_url_prefix = "http://101.132.64.6:10005/aifile"

# 创建 OpenAI 客户端
client = OpenAI(api_key=STEP_API_KEY, base_url=BASE_URL)


# 从日志文件中提取出失败的视频路径
def extract_failed_video_paths(log_file_path):
    failed_videos = []
    video_path_pattern = re.compile(r"视频路径:\s*(.+)")
    error_line_pattern = re.compile(r"处理视频时发生错误:")

    with open(log_file_path, "r", encoding="utf-8") as f:
        lines = f.readlines()

    for i in range(len(lines)):
        if error_line_pattern.search(lines[i]):
            # 查找上一行是否是视频路径
            if i > 0 and video_path_pattern.search(lines[i - 1]):
                video_path = video_path_pattern.search(lines[i - 1]).group(1)
                failed_videos.append(video_path.strip())

    return failed_videos


# 日志打印函数（终端 + 文件）
def log_print(*args, **kwargs):
    message = " ".join(map(str, args))
    print(message, **kwargs)
    log_file.write(message + "\n")
    log_file.flush()


# 主程序入口
if __name__ == "__main__":
    log_file_path = "20250625_101727_retry.txt"
    output_log_file = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + "_retry.txt"

    failed_videos = extract_failed_video_paths(log_file_path)

    if not failed_videos:
        print("没有找到需要重试的视频。")
        exit()

    print(f"共发现 {len(failed_videos)} 个失败视频，开始重试...\n")

    # 打开日志文件用于写入
    with open(output_log_file, "w", encoding="utf-8") as log_file:

        for idx, video_key in enumerate(failed_videos):
            vedio_path1 = f"{base_url_prefix}/{video_key}"
            log_print(f"\n【视频 {idx + 1}/{len(failed_videos)}】")
            log_print(f"视频路径: {video_key}")

            messages = [
                {
                    "role": "user",
                    "content": [
                        {"type": "video_url", "video_url": {"url": vedio_path1}},
                        {"type": "text", "text": user_prompt}
                    ]
                }
            ]

            time_start = time.time()
            try:
                response = client.chat.completions.create(
                    model=COMPLETION_MODEL,
                    messages=messages,
                    stream=True
                )

                full_response = ""
                for chunk in response:
                    if chunk.choices[0].delta.content:
                        content = chunk.choices[0].delta.content
                        full_response += content

                log_print("\n分析结果：")
                log_print(full_response)

            except Exception as e:
                log_print(f"处理视频时发生错误: {e}")

            time_end = time.time()
            log_print(f"\n总生成时间: {time_end - time_start:.2f}秒")

            # 添加延迟避免限速
            time.sleep(2)